package cn.ytr.crm.shiro;

import cn.ytr.crm.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

@Component("crmFormAuthenticationFilter")
public class CRMFormAuthenticationFilter extends FormAuthenticationFilter{

    /**
     * 复写登录成功后处理的方法
     */
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
                                     ServletRequest request, ServletResponse response) throws Exception {
        //响应 json 字符串数据
        JsonResult json = new JsonResult();
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(json));
        //不放行
        return false;
    }

    /**
     * 复写登录失败后处理的方法
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e,
                                     ServletRequest request, ServletResponse response) {
        //响应 json 字符串数据
        JsonResult json = new JsonResult();
        response.setContentType("application/json;charset=utf-8");
        json.mark("登录失败，用户名和密码不匹配");
        try {
            response.getWriter().write(JSON.toJSONString(json));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        //不放行
        return false;
    }

}























